﻿using System;
using Un4seen.Bass;

namespace Theta.Audio
{
    //Todo: Support multiple sounds (Return handle and let user fuck with that)
    public class SoundPlayer : IDisposable
    {
        public string MusicFileName;
        float _volume;
        int _handle;

        public SoundPlayer(string filename)
        {
            if(Core.Audio == null || !Core.Audio.IsInitialized)
                throw new Exception("Audio engine is not initialized, call Core.Audio.Initialize before using any sound related features");

            MusicFileName = filename;
            LoadStream();
        }

        internal void LoadStream()
        {
            if(_handle != 0)
                Bass.BASS_StreamFree(_handle);

            _handle = Bass.BASS_StreamCreateFile(MusicFileName, 0, 0, BASSFlag.BASS_DEFAULT);
        }

        public void Play()
        {
            Bass.BASS_ChannelPlay(_handle, true);
        }

        public void Resume()
        {
            Bass.BASS_ChannelPlay(_handle, false);
        }

        public void Pause()
        {
            Bass.BASS_ChannelPause(_handle);
        }
        
        public void Stop()
        {
            Bass.BASS_ChannelStop(_handle);
        }

        public void SetVolume(float volume)
        {
            Bass.BASS_ChannelSetAttribute(_handle, BASSAttribute.BASS_ATTRIB_VOL, volume);
        }

        public void NewSound(string filename)
        {
            Stop();
            Bass.BASS_StreamFree(_handle);
            MusicFileName = filename;
            LoadStream();
        }

        public void Dispose()
        {
            if (_handle != 0)
                Bass.BASS_StreamFree(_handle);
        }
    }
}
